#include <iostream>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <fcntl.h>
#include <json/json.h>

#include "hbase_client.h"
#include "connpool.h"
#include "json.h"
#include "base/base.h"
#include "error_code.h"
#include "command.h"
#include "datainit.h"

#include <fcgi_stdio.h>
using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace apache::hadoop;

using namespace boost;

ConnPool *connpool;

int get(char *table)
{
	RowResult *row;
	struct hbase_conn *hconn;
	while (1) {
		hconn = (struct hbase_conn *)connpool->get(CONN_POOL_TYPE_HBASE);

		if (hconn == NULL) {
			DERROR("get null\n");
			return -1;
		}

		HbaseOp *conn = hconn->conn;
		row = conn->get(table, "9769596");
		if (row == NULL) {
			connpool->put(CONN_POOL_TYPE_HBASE, hconn);
			DERROR("hbase get error: %d\n", conn->errnum);
			return -1;
		}
		connpool->put(CONN_POOL_TYPE_HBASE, hconn);
		break;
	}

	ColumnValue *cv;
	cout << "ROW\tCOL\tVALUE\tTIMESTAMP\n" << row->row;
	while (cv = row->nextcolumn()) {
		cout << "\t" << cv->column << "\t" << cv->value << "\t" << cv->timestamp << endl;
	}
	row->free();
	delete(row);
	return 0;
}

int scan (char *table)
{
	int fd = open("scan.txt", O_WRONLY|O_CREAT, 0600);
	if (fd < 0) {
		DERROR("create file error\n");
		return -1;
	}

	struct hbase_conn *hconn = (struct hbase_conn *)connpool->get(CONN_POOL_TYPE_HBASE);
	if (hconn == NULL) {
		DERROR("can't get one conn\n");
		return(-1);
	}

	HbaseOp *conn = hconn->conn;
	struct ColumnValue col1;
	struct ColumnValue col2;
	col1.column = "col";
	//col2.column = "col1:mail";
	//col1.next = &col2;
	int ret = conn->scanOpenWithPrefix(table, "2011-09-07", &col1);
	if (ret < 0) {
		DERROR("scan open error\n");
		exit(-1);
	}

	int i;
	for (i = 0;; i++) {
		RowResult *rows = conn->scan(100);
		RowResult *row;
		if (rows == NULL)
			break;
		while (row = rows) {
			write(fd, row->row.c_str(), strlen(row->row.c_str()));
			write(fd, "\n", 1);
/*
			DINFO("row key-->%s\n", row->row.c_str());
			struct ColumnValue *cv;
			while (cv = row->nextcolumn()) {
				DINFO("\t%s --> %s\n", cv->column.c_str(), cv->value.c_str());
			}
			DINFO("\n");
*/
			rows = rows->next;
			row->free();
			delete(row);
		}
	}

	conn->scanclose();
	connpool->put(CONN_POOL_TYPE_HBASE, hconn);
}

int create(char *table)
{
	struct ColumnValue col1;
	col1.column = "col1";
	struct ColumnValue col2;
	col2.column = "col2";
	col1.next = &col2;

	struct hbase_conn *hconn = (struct hbase_conn *)connpool->get(CONN_POOL_TYPE_HBASE);
	if (hconn == NULL) {
		DERROR("hbase conn full\n");
		return -1;
	}
	HbaseOp *conn = hconn->conn;
	int ret = conn->create(table, &col1);
	if (ret < 0) {
		DERROR("hbase create error: %d\n", conn->errnum);
	}
	DERROR("create hbase: %d\n", CONN_POOL_TYPE_HBASE);
	connpool->put(CONN_POOL_TYPE_HBASE, hconn);
	return ret;
}

int deletetable(char *table)
{
	cmd_remove(table);
/*
    struct hbase_conn *hconn = (struct hbase_conn *)connpool->get(CONN_POOL_TYPE_HBASE);
    if (hconn == NULL) {
        DERROR("hbase conn full\n");
        return -1;
    }
    HbaseOp *conn = hconn->conn;
    int ret = conn->delete_table(table);
    if (ret < 0)
        DERROR("hbase delete table error: %d\n", conn->errnum);
    connpool->put(CONN_POOL_TYPE_HBASE, hconn);
*/
    return 0;
}

int del(char *table)
{
	FILE *fp = fopen("scan.txt", "r");
	if (!fp) {
		DERROR("open file error\n");
		return -1;
	}

	struct hbase_conn *hconn = (struct hbase_conn *)connpool->get(CONN_POOL_TYPE_HBASE);
	if (hconn == NULL) {
		DERROR("hbase conn full\n");
		return -1;
	}
/*
	struct ColumnValue col1;
	col1.column = "col1:id";
	struct ColumnValue col2;
	col2.column = "col2:addr";
	col1.next = &col2;
	HbaseOp *conn = hconn->conn;
	int ret = conn->del(table, "1", &col1);
	if (ret < 0)
		DERROR("hbase del error: %d\n", conn->errnum);
*/

	HbaseOp *conn = hconn->conn;
	char row[1024];
	while(fgets(row, 1024, fp)) {
		row[strlen(row)-1] = '\0';
		if (strlen(row) == 0)
			continue;
		int ret = conn->del(table, row);
		if (ret < 0)
			DERROR("hbase del error: %d\n", conn->errnum);
	}
	connpool->put(CONN_POOL_TYPE_HBASE, hconn);
	return 0;
}

int put(char *table)
{
	struct hbase_conn *hconn = (struct hbase_conn *)connpool->get(CONN_POOL_TYPE_HBASE);
	if (hconn == NULL) {
		DERROR("hbase conn full\n");
		return -1;
	}
	HbaseOp *conn = hconn->conn;
	int ret;
	srand(time(NULL));
	struct timeval startime, endtime;
	long i,j;
	struct RowResult *rows = NULL;
	struct RowResult *row;
	gettimeofday(&startime, NULL);
	for (j = 0; j < 100000; j++) {
		rows = NULL;
		for (i = 0; i < 100; i++) {
			char rowbuf[1024];
			row = new (struct RowResult);
			sprintf(rowbuf, "%d.%d", j, i);
			row->row = rowbuf;

			sprintf(rowbuf, "%u", i);
			row->insert("col:id", rowbuf, 0);

			sprintf(rowbuf, "mail@gmail.com");
			row->insert("col:mail", rowbuf, 0);

			sprintf(rowbuf, "%u", rand()%1000000);
			row->insert("col:random", rowbuf, 0);

			sprintf(rowbuf, "haidianqu,qinghuakejiyuan%d", i);
			row->insert("col:addr", rowbuf, 0);

			sprintf(rowbuf, "%d,%d", j, i);
			row->insert("col:coordination", rowbuf, 0);

			row->next = rows;
			rows = row;
		}
		ret = conn->put(table, rows);
		if (ret < 0) {
			DERROR("hbase put error: %d\n", conn->errnum);
		}
		while(row=rows) {
			rows = rows->next;
			row->free();
		}
	}
	gettimeofday(&endtime, NULL);

	time_t secs = timediff(&startime, &endtime)/1000000;

	connpool->put(CONN_POOL_TYPE_HBASE, hconn);
	DERROR("qps: %d\n", 10000000/secs);
	return ret;
}

int main(int argc, char **argv)
{
	int i;
	int ret;
	int num = 2;
	char buf[1024];

	logfile_create("test.log", 4);

	ret = dataserver_init("dp.conf");
	if (ret < 0) {
		DERROR("connpool init error\n");
		exit(-1);
	}
	connpool = g_rt->cp;
	deletetable(argv[1]);
	//del(argv[1]);
	//create(argv[1]);
	//put(argv[1]);
	//get(argv[1]);
	//scan(argv[1]);
	exit(0);
/*
	Json::Value root;
	Json::Value arrayObj;
	Json::Value item;

	char *store = "hbase";
	char *fields = "   id,				name,age,  testaa,  mail,addr";
	char *rowkey = "id";
	char *addr = "19.2.172.51";
	char *desc = "table name";

	ret = cmd_create(argv[1], store, fields, rowkey, addr, desc);
	if (ret < 0) {
		printf("cmd_create error: %d\n", ret);
	}

	for (i = 0; i < 4; i++) {
		char str[1024];
		snprintf(str, 1024, "%d", i);
		item["id"] = str;
		snprintf(str, 1024, "name_%d", i);
		item["name"] = str;
		snprintf(str, 1024, "addr_%d", i);
		item["addr"] = str;
		snprintf(str, 1024, "%d", i+80);
		item["time"] = str;
		arrayObj.append(item);
	}

	root["array"] = arrayObj;
	std::string json = root.toStyledString();
	cout << json.c_str() << endl;
*/
/*
	char *jsonstr = "{\"array\":[{\"rkey_id\":\"70efd68b-f5df-4a36-9369-25454b400a78\",\"userid\":\"12363455\",\"username\":\"值班编辑046\",\"client_ip\":\"59.50.94.161\",\"data_time\":\"2011-07-11 17:47:46\",\"operation\":\"logout\",\"domain\":\"passport.tianya.cn\",\"server_ip\":\"19.2.172.89\"},{\"rkey_id\":\"dd063802-4cfd-493a-8ac8-37ded1ac59dd\",\"userid\":\"40742915\",\"username\":\"wuzongbao2010\",\"client_ip\":\"121.33.201.170\",\"data_time\":\"2011-07-11 18:04:50\",\"operation\":\"login\",\"domain\":\"passport.tianya.cn\",\"server_ip\":\"19.2.172.89\"},{\"rkey_id\":\"d32027ad-c065-40f7-a8cf-a7d591564b2a\",\"userid\":\"7077688\",\"username\":\"xiayuan99\",\"client_ip\":\"121.33.201.170\",\"data_time\":\"2011-07-11 18:28:55\",\"operation\":\"login\",\"domain\":\"passport.tianya.cn\",\"server_ip\":\"19.2.172.89\"},{\"rkey_id\":\"cb4a85b5-705f-4ce6-812d-f4a6a0ee6f1b\",\"userid\":\"17113994\",\"username\":\"茹墨\",\"client_ip\":\"121.33.201.170\",\"data_time\":\"2011-07-11 18:40:07\",\"operation\":\"login\",\"domain\":\"passport.tianya.cn\",\"server_ip\":\"19.2.172.89\"},{\"rkey_id\":\"866fbd95-6e25-45cf-a698-105ac9a64264\",\"userid\":\"17113994\",\"username\":\"茹墨\",\"client_ip\":\"121.33.201.170\",\"data_time\":\"2011-07-11 18:45:22\",\"operation\":\"logout\",\"domain\":\"passport.tianya.cn\",\"server_ip\":\"19.2.172.89\"},{\"rkey_id\":\"326af6ef-2e69-4ef3-8337-8b33f3e52c55\",\"userid\":\"25035067\",\"username\":\"yaohuilike\",\"client_ip\":\"123.103.97.58\",\"data_time\":\"2011-07-11 18:56:22\",\"operation\":\"login\",\"domain\":\"ice1\",\"server_ip\":\"\\\\N\"},{\"rkey_id\":\"119adaa8-407d-489f-8adc-0744087821e5\",\"userid\":\"53760067\",\"username\":\"hejj8822\",\"client_ip\":\"123.103.97.58\",\"data_time\":\"2011-07-11 20:37:07\",\"operation\":\"login\",\"domain\":\"ice1\",\"server_ip\":\"\\\\N\"},{\"rkey_id\":\"1dd7104d-9a7a-4742-a20b-d00758e06576\",\"userid\":\"40685231\",\"username\":\"值班编辑057\",\"client_ip\":\"59.50.94.161\",\"data_time\":\"2011-07-11 21:21:07\",\"operation\":\"online\",\"domain\":\"blog.tianya.cn\",\"server_ip\":\"19.2.172.89\"},{\"rkey_id\":\"b47b3605-11a2-40fc-964a-3baf34d9d8f7\",\"userid\":\"12363459\",\"username\":\"值班编辑050\",\"client_ip\":\"59.50.94.161\",\"data_time\":\"2011-07-11 21:29:02\",\"operation\":\"login\",\"domain\":\"passport.tianya.cn\",\"server_ip\":\"19.2.172.89\"},{\"rkey_id\":\"526b0afa-5b74-4f37-9cec-467de025b8dc\",\"userid\":\"40685231\",\"username\":\"值班编辑057\",\"client_ip\":\"59.50.94.161\",\"data_time\":\"2011-07-11 21:30:14\",\"operation\":\"online\",\"domain\":\"blog.tianya.cn\",\"server_ip\":\"19.2.172.89\"}]}";
	struct RowResult *rows = parse_json(argv[1], jsonstr, strlen(jsonstr));
	struct RowResult *row;
	/if (rows == NULL) {
		cout << "parse_json: return null" << endl;
		exit(-1);
	}
	while (row = rows) {
		ColumnValue *cv;
		cout << "rowkey: " << row->row << endl;
		while (cv = row->nextcolumn()) {
			cout << cv->column << "\t" << cv->value << endl;
		}

		rows = rows->next;
		row->free();
		delete(row);
		cout << endl;
	}
	char *d = "[{\"id\":1, \"name\":\"ladeng\", \"addr\":\"afuhan\", \"age\":99}, {\"id\":2, \"name\":\"m\", \"addr\":\"afuhan\", \"age\":80}, {\"id\":3, \"name\":\"m\", \"addr\":\"afuhan\", \"age\":80}, {\"id\":4, \"name\":\"m\", \"addr\":\"afuhan\", \"age\":80}]";
	ret = cmd_add(argv[1], json.c_str(), strlen(json.c_str()));
	if (ret != 0) {
		printf("cmd_add error: %d\n", ret);
	}
*/

	close_connpool(connpool);
	exit(0);
}
